package com.hudongwx.godoffood.fragment.myFragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.activity.home_activity.FoodClassificationActivity;
import com.hudongwx.godoffood.activity.home_activity.FoodGoodsPageActivity;
import com.hudongwx.godoffood.utils.MyApplication;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_already_failed)
public class AlreadyFailedFragment extends Fragment {
    @ViewInject(R.id.my_community_msg_failed_rl_content)
    private RecyclerView recyclerView;
    @ViewInject(R.id.my_already_failed_rl)
    private RelativeLayout relativeLayout;
    private MyOrderAdapter myOederAdapter;
    private String TAG = "AlreadyFailedFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        LinearLayoutManager linear = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linear);
        String orderJsonData = MyApplication.getOrderJsonData();
        if (null != orderJsonData) {
            try {
                JSONObject data = new JSONObject(orderJsonData);
                myOederAdapter = new MyOrderAdapter(data.getJSONArray("Data"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            recyclerView.setAdapter(myOederAdapter);
        }

        return view;
    }

    private void loadData() {
//        Date now = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
//        String time = dateFormat.format(now);
//        Log.i(TAG, "loadData: "+time);
        String allOrderUrl = "http://api.shiandianping.com/api/sourceAndroidDianPing/v3.1.0/Order?timestamp=2016-11-10%2020:15:42&Pageindex=1&Pagesize=5&token=091b08ca-a083-4e01-8699-6f833e229aed&Type=-1&signature=b4f395aacc9d4e183649b17a194154d4c96a4a2e";
        RequestParams requestParams = new RequestParams(allOrderUrl);
        x.http().get(requestParams, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONArray data = result.getJSONArray("Data");
                    Log.i(TAG, "onSuccess:   我的数据：-------------    " + data);
                    if (0 == data.length()) {
                        recyclerView.setVisibility(View.GONE);
                        relativeLayout.setVisibility(View.VISIBLE);
                    } else {
                        MyApplication.setOrderJsonData(result.toString());
                        myOederAdapter = new MyOrderAdapter(data);
                        recyclerView.setAdapter(myOederAdapter);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    class MyOrderAdapter extends RecyclerView.Adapter<MyViewHolder> {
        JSONArray data;

        public MyOrderAdapter(JSONArray data) {
            this.data = data;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.my_order_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            try {
                JSONObject item = data.getJSONObject(position);
                JSONObject orderItems = item.getJSONArray("OrderItems").getJSONObject(0);
                Log.i(TAG, "onBindViewHolder:  orderItems :  " + orderItems);
                holder.tvNumber.setText(item.getString("orderid"));
                holder.tvStatus.setText(item.getString("OrderStatus"));
                holder.tvName.setText(orderItems.getString("ShortName"));
                holder.tvWeight.setText(orderItems.getString("SPEC"));
                holder.tvPrice.setText("￥" + orderItems.getString("UNITPRICE"));
                holder.tvTime.setText(item.getString("orderdate"));
                holder.tvNum.setText("X" + orderItems.getString("Num"));
                holder.tvTruePrice.setText(item.getInt("money") + "");
                x.image().bind(holder.ivIcon, orderItems.getString("ProductImg"));
                String productID = orderItems.getString("productID");
                String[] strings = toArra(productID);
                holder.linearLayout.setTag(strings);
                holder.linearLayout.setOnClickListener(new ClickItem());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            return data.length();
        }
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvNumber, tvStatus, tvName, tvWeight, tvPrice, tvNum, tvTime, tvTruePrice;
        ImageView ivIcon;
        LinearLayout linearLayout;

        public MyViewHolder(View itemView) {
            super(itemView);
            tvNumber = (TextView) itemView.findViewById(R.id.my_order_item_number);
            tvName = (TextView) itemView.findViewById(R.id.my_order_item_tv_name);
            tvWeight = (TextView) itemView.findViewById(R.id.my_order_item_tv_weight);
            tvPrice = (TextView) itemView.findViewById(R.id.my_order_item_tv_price);
            tvNum = (TextView) itemView.findViewById(R.id.my_order_item_tv_num);
            tvTime = (TextView) itemView.findViewById(R.id.my_order_item_tv_time);
            tvStatus = (TextView) itemView.findViewById(R.id.my_order_item_status);
            tvTruePrice = (TextView) itemView.findViewById(R.id.my_order_item_tv_true_price);
            ivIcon = (ImageView) itemView.findViewById(R.id.my_order_item_iv_icon);
            linearLayout = (LinearLayout) itemView.findViewById(R.id.my_order_item_ll);

        }
    }
    //把传过来的id 加载出一个和一组商品的id
    private String[] toArra(String productID){
        String id = "";
        if (productID.contains("D")) {
            id = productID.replaceAll("_D", "");
            Log.i(TAG, "onBindViewHolder: =====================" + id);
        } else {
            id = productID + "_D";
        }
        //跳
        String msg[] = {productID, id};
        return msg;
    }

    class ClickItem implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), FoodGoodsPageActivity.class);
            intent.putExtra("productID", (String[]) v.getTag());
            startActivity(intent);
        }
    }

    @Event(R.id.all_order_go_see)
    private void goSee(View view) {
        startActivity(new Intent(getActivity(), FoodClassificationActivity.class));
    }

}